<template>
    <el-card shadow="hover" class="mb5 mt5">
        <template #header>
            <!-- <div class="processhandle-card-header"> -->
                <el-space>
                    <vp-label zh="流程处理" en="Process Handle"/>
                    <el-popover placement="right" :width="550" trigger="click"  v-if="processInsId">
                        <template #reference>
                            <el-link type="primary">{{'流程记录/Process Record'}}</el-link> &nbsp;
                        </template>
                        <ProcessHistory  :processInsId="processInsId" />
                    </el-popover>
                    <el-popover placement="right" :width="850" trigger="click" v-if="processInsId" >
                        <template #reference>
                            <el-link type="primary">{{'流程图/Process Chart'}}</el-link>
                        </template>
                        <ProcessView  :processInsId="processInsId" />
                    </el-popover>
                </el-space>
            <!-- </div> -->
        </template>
        <el-form label-suffix=":" v-loading="loading"  :model="formData" :rules="formRules" ref="formRef" :label-width="labelWidth">
            <el-row>
                <vp-col :span=2>
                    <el-form-item :label="$t('workflow.priority')" prop="priority">
                        <template #label><vp-label zh="优先级" en="Priority" align="left"/></template>
                        <el-radio-group size="small" v-model="formData.priority" class="w100">
                            <!-- <el-radio-button :label="10">{{ $t('workflow.priority10') }}</el-radio-button> -->
                            <el-radio-button :label="20"><vp-label  zh="紧急" en="Urgent"/></el-radio-button>
                            <el-radio-button :label="30"><vp-label zh="急" en="High"/></el-radio-button>
                            <el-radio-button :label="40"><vp-label zh="一般" en="Normal"/></el-radio-button>
                            <!-- <el-radio-button :label="50">{{ $t('workflow.priority50') }}</el-radio-button> -->
                        </el-radio-group>
                    </el-form-item>
                </vp-col>
            </el-row>
            <el-row v-if="showOperate">
                <vp-col :span=2>
                     <el-form-item :label="$t('item.operation')" prop="operate">
                        <template #label><vp-label zh="操作" en="Operation" align="left"/></template>
                        <el-radio-group size="small" v-model="formData.operate" @change="handleChangeOperate">
                            <el-radio-button label="completed"><vp-label zh="同意" en="Completed"/></el-radio-button>
                            <el-radio-button v-if="showReject && processInsId && nextSteps.length > 0" label="reject"><vp-label zh="驳回" en="Reject"/></el-radio-button>
                            <el-radio-button v-if="processInsId" label="transfer"><vp-label zh="转办" en="Transfer"/></el-radio-button>
                            <el-radio-button v-if="processInsId" label="delegate"><vp-label zh="委派/沟通" en="Delegate"/></el-radio-button>
                            <el-radio-button v-if="showCancel && processInsId" label="cancel"><vp-label zh="中止" en="Cancel"/></el-radio-button>
                        </el-radio-group>
                    </el-form-item>
                </vp-col>
                <vp-col :span=2>
                    <el-form-item v-if="formData.operate === 'reject'" :label="$t('workflow.task.nextStep')" prop="nextStep">
                        <template #label><vp-label zh="下一环节" en="Next Step" align="left"/></template>
                        <el-select v-model="formData.nextStep" placeholder="Select">
                            <el-option
                                v-for="item in filterNextSteps"
                                :key="item.id"
                                :label="item.activityName"
                                :value="item.activityId"
                            >
                            </el-option>
                        </el-select>    
                    </el-form-item>
                    <el-form-item v-if="formData.operate === 'transfer' || formData.operate === 'delegate'" :label="$t(`workflow.task.operate.${formData.operate}`)" prop="nextUserId">
                        <template #label>
                            <vp-label v-if="formData.operate === 'transfer'" zh="转办" en="Transfer" align="left"/>
                            <vp-label v-if="formData.operate === 'delegate'" zh="委派/沟通" en="Delegate" align="left"/>
                        </template>
                        <VpUserSelect
                            :selectedId="formData.nextUserId"
                            @userSelected="userSelected"
                            class="w100"
                        ></VpUserSelect>
                    </el-form-item>
                </vp-col>
            </el-row>
            <el-row>
                <slot></slot>
            </el-row>
            <el-row v-if="showComments">
                <vp-col :span=1>
                     <el-form-item :label="$t('item.comments')" prop="comments" 
                        :rules="(formData.operate === 'reject' || formData.operate === 'cancel')?[
                            validateUtils.notNull,
                        ]:[]"
                    >
                        <template #label><vp-label zh="说明" en="Comments" align="left"/></template>
                        <el-input type="textarea" v-model="formData.comments" maxlength="1000"></el-input>
                    </el-form-item>
                </vp-col>
            </el-row>
            <el-row v-if="showComments">
                <vp-col :span=1>
                     <el-form-item :label="$t('item.attachment')" prop="attachments">
                        <template #label><vp-label zh="附件" en="Attachment" align="left"/></template>
                        <VpRowAttachment v-model:attachmentList="formData.attachments" @attachmentListEmit="getAttachmentListEmit($event,formData)"></VpRowAttachment>
                    </el-form-item>
                </vp-col>
            </el-row>
        </el-form>
    </el-card>
</template>
<script lang="ts" setup name="processHandle">
import { computed, defineComponent, onMounted, reactive, ref, toRefs } from 'vue'
import VpRowAttachment from '../file/VpRowAttachment.vue';
import request from '/@/utils/request';
import validateUtils from '/@/utils/validateUtils';
import { i18n } from '/@/i18n';
import VpUserSelect from "/@/components/vp/user/VpUserSelect.vue";
import ProcessHistory from "/@/components/vp/workflow/ProcessHistory.vue";
import ProcessView from "/@/components/vp/workflow/ProcessView.vue";

    const props = withDefaults(defineProps<{
        processInsId: string,
        taskId: string,
        label?:  string,
        labelWidth?: string,
        showOperate?: boolean,
        showCancel?: boolean,
        showReject?: boolean,
        isNew?: boolean,
        showComments?:boolean,
        rejectLastNode?:boolean,
    }>(), {
        label: '流程处理/Process Handle',
        labelWidth:  '120px',
        showOperate: true,
        showCancel: false,
        showReject: true,
        isNew: false,
        showComments: true,
        rejectLastNode: false,
    });

    const emits = defineEmits(['operateChanged']);

    const loading = ref(false);

    const formData = ref({
        priority: 40,
        comments: "",
        operate: "completed",
        nextStep: "",
        nextUserId: "",
        attachments: [],
    });

    const formRules = {
        operate:[
            validateUtils.notNull,
        ],
        nextUserId:[
            validateUtils.notNull,
        ],
    }

    const nextSteps = ref([]);

    const filterNextSteps = computed(() => {
        // 仅可驳回至上一节点
        if (props.rejectLastNode && nextSteps.value.length > 0) {
            return nextSteps.value.slice(nextSteps.value.length - 1);
        }
        return nextSteps.value;
    })

    onMounted(()=>{
            if(props.processInsId && props.taskId){
                request.get(`/workflow/process/finished/${props.processInsId}/${props.taskId}`).then((res)=>{
                    nextSteps.value = res?.data || [];
                    if(nextSteps.value && nextSteps.value.length > 0){
                        formData.value.nextStep = filterNextSteps.value[0].activityId;
                    }
                })
            }
        })

        const formRef = ref();
        const getFormData =  (): Promise<any>=>{
            let promise = new Promise((resolve, reject) => {
                formRef.value.validate((valid: boolean) => {
                    if (valid) {
                        
                        resolve(formData.value);
                    } else {
                        reject();
                    }
                })
            })
            return promise;
        }
        const getAttachmentListEmit = (data: any, row: any)=>{
            row.attachments = data;
        }

        const handleChangeOperate =()=>{
           if(formData.value.operate === "completed"){
                formData.value.comments = "";
                emits('operateChanged', true);
           }else if(formData.value.operate === "reject"){
                formData.value.comments = "驳回";
                emits('operateChanged', false);
           }else{
                formData.value.comments = "";
                emits('operateChanged', false);
           }
        }

        const getOperate = ()=>{
            return formData.value.operate === "completed";
        }

        const userSelected = (item: any) => {
            formData.value.nextUserId = item.id;
        }

        const getProcessVariable = (keys: string[]): Promise<any>=>{
            return request.get(`/workflow/process/variable`, {
				params: {
                    processInsId: props.processInsId,
					keys: keys,
				}
			});
        }

        defineExpose({
            getOperate,
            getFormData
        })


</script>
<style scoped lang="scss">
.processhandle-card-header {
//   display: flex;
//   justify-content: space-between;
//   align-items: center;
}
</style>